package net.jiupinshi.service.goods.impl;

import net.jiupinshi.MainApplication;
import net.jiupinshi.dao.GoodsCategoryDao;
import net.jiupinshi.dto.CategoryDTO;
import net.jiupinshi.entity.GoodsCategory;
import net.jiupinshi.service.goods.GoodsCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Despription: 需要修改
 * @Author: penghui.guo
 * @Date: 2018/12/16 15:20
 */
@Service
public class GoodsCategoryServiceImpl implements GoodsCategoryService {

    @Autowired
    GoodsCategoryDao goodsCategoryDao;

    @Override
    public List<CategoryDTO> getCategorys() {
        List<GoodsCategory> goodsCategories =  goodsCategoryDao.getCategorys();
        Iterator<GoodsCategory> it = null;
        List<CategoryDTO> list = new ArrayList<>();
        CategoryDTO categoryDTO = null;
        GoodsCategory goodsCategory = null;
        Map<Long, List<CategoryDTO>> map = new HashMap<>();
        for (int i = 0; i < 2; i++){
            it = goodsCategories.iterator();
            while (it.hasNext()){
                goodsCategory = it.next();
                categoryDTO = new CategoryDTO();
                if (i == 0){
                    if (goodsCategory.getParentId() == 0){
                        categoryDTO.setId(goodsCategory.getId());
                        categoryDTO.setName(goodsCategory.getName());
                        list.add(categoryDTO);
                        it.remove();
                    }
                }else {
                    List<CategoryDTO> list1 = new ArrayList<>();
                    Long parentId = goodsCategory.getParentId();
                    if(map.get(parentId) != null){
                        list1 = map.get(parentId);
                    }
                    categoryDTO.setId(goodsCategory.getId());
                    categoryDTO.setName(goodsCategory.getName());
                    list1.add(categoryDTO);
                    map.put(parentId, list1);
                }
            }

        }
        for (CategoryDTO categoryDTO1 : list){
            categoryDTO1.setCategoryDTOS(map.get(categoryDTO1.getId()));
        }
        return list;
    }


}
